package com.game.modular.gameCore.map.service.impl;

import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.game.modular.gameCore.map.mapper.CoreCityLinkMapper;
import com.game.modular.gameCore.map.domain.CoreCityLink;
import com.game.modular.gameCore.map.service.CoreCityLinkService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 城池关联(CoreCityLink)表服务实现类
 *
 * @author cxy
 * @since 2024-07-30 20:45:36
 */
@Slf4j
@Service
public class CoreCityLinkServiceImpl extends ServiceImpl<CoreCityLinkMapper, CoreCityLink> implements CoreCityLinkService {
    Cache<String, Map<Integer,CoreCityLink>> cache = Caffeine.newBuilder().build();
    
    @PostConstruct
    private void init() {
        CoreCityLink initSelect = CoreCityLink.builder().build();
        List<CoreCityLink> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存城池关联数据,数据量为:{}",list.size());
        cache.put(
                "coreCityLink", 
                list.stream().collect(Collectors.toMap(CoreCityLink::getId, CoreCityLink -> CoreCityLink))
        );
        log.info("城池关联数据缓存完成");
    }

    public List<CoreCityLink> listCache() {
        Map<Integer,CoreCityLink> values = cache.getIfPresent("coreCityLink");
        if (Objects.isNull(values)) {
            throw new RuntimeException("城池关联数据为空");
        }
        return new ArrayList<>(values.values());
    }   
    
    public CoreCityLink getCache(Integer id) {
        return listCache().get(id);
    }
}
